﻿using System.Web;
using MigSharp;

namespace CmsDatabaseMigrations.Web.Handlers
{
    public class DatabaseMigrations : IHttpHandler
    {
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param>
        public void ProcessRequest(HttpContext context)
        {
            var options = new MigrationOptions();            
            options.SupportedProviders.Set(new []{ProviderNames.SqlServer2008});
            var migrator = new Migrator(MigrationsConfiguration.ConnectionString, ProviderNames.SqlServer2008, options);
            
            var batch = migrator.FetchMigrationsTo(MigrationsConfiguration.PathToMigrationsAssembly, long.MaxValue);            
            
            batch.Execute();
            context.Response.Write("Migrations have been applied.");
        }

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <returns>
        /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        /// </returns>
        public bool IsReusable
        {
            get { return true; }
        }
    }
}